package com.minivision.fdiot.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.minivision.fdiot.common.ChunkRequest;
import com.minivision.fdiot.common.CommonConstants;
import com.minivision.fdiot.entity.MqttLog;
import com.minivision.fdiot.repository.mysql.MqttLogRepository;
import com.minivision.fdiot.rest.param.MqttLogParam;
import com.minivision.fdiot.rest.param.QueryMqttLogParam;

@Service
public class MqttLogServiceImpl extends BaseService implements MqttLogService {
  
  @Autowired
  private MqttLogRepository mqttLogRepo;

  @Override
  public MqttLog create(MqttLog log) {
    return mqttLogRepo.saveAndFlush(log);
  }

  @Override
  public Page<MqttLog> findByCreateTimeBetween(MqttLogParam param) throws Exception {
    SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.FULL_DATE_FORMAT);
    Date startDate = sdf.parse(param.getStartTime());
    Date endDate = sdf.parse(param.getEndTime());
    return mqttLogRepo.findByCreateTimeBetweenOrderByCreateTimeDesc(startDate, endDate, new ChunkRequest(param.getOffset(), param.getLimit()));
  }

  @Override
  public void delete(Long id) {
    mqttLogRepo.delete(id);
  }

  @Override
  public MqttLog find(Long id) {
    return mqttLogRepo.findOne(id);
  }

  @Override
  public List<MqttLog> findByDeviceSn(String deviceSn) {
    return mqttLogRepo.findByDeviceSn(deviceSn);
  }

  @Override
  public List<MqttLog> findByDeviceSnAndCmdCode(String deviceSn, int cmdCode) {
    return mqttLogRepo.findByDeviceSnAndCmdCode(deviceSn, cmdCode);
  }

  @Override
  public Page<MqttLog> findByPage(QueryMqttLogParam param) {
    ExampleMatcher matcher = ExampleMatcher.matching()
        .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
        .withIgnoreCase(true);
    MqttLog logExample = new MqttLog();
    BeanUtils.copyProperties(param, logExample);
    Example<MqttLog> example = Example.of(logExample, matcher);
    return mqttLogRepo.findAll(example, new ChunkRequest(param.getOffset(), param.getLimit(), new Sort(Direction.DESC, "updateTime")));
  }

}
